package UserInterface;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;

import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import DataReading.LoadSystem;
import DataReading.Vessel;
import DataReading.VesselList;

public class gridUI extends JFrame {
	
	public JTextField timerField;
	private JPanel buttonPanel;
	private JPanel sliderPanel;
	private JPanel checkBoxPanel;
	private JPanel radarPanel;
	private JLabel vessels;
	public JButton startPauseButton;
	public JButton gridBackButton; // back button
	private JButton tableFromGrid; // button that links to table from the grid
	private JButton dualView;
	public static JSlider slider;
	private JLabel timeStep;
	public JCheckBox swimmer;
	public JCheckBox speedBoat;
	public JCheckBox fishingBoat;
	public JCheckBox cargoVessel;
	public JCheckBox passengerVessel;
	final int WINDOW_WIDTH = 900;
	final int WINDOW_HEIGHT = 870;
	private initUI init;
	private tableUI table;
	private LoadSystem system;
	//public Timer timer = new Timer(initUI.currentSliderValue, new TimerListener());
	//tprivate double timeToSend = 0;
	private int index = 0;
	private int xPosition = 0;
	private int yPosition = 0;
	Shape circleHuman = new Ellipse2D.Double(xPosition,yPosition,10,10); // human (swimmer)
	Shape circleSpeed = new Ellipse2D.Double(xPosition,yPosition,10,10); // speed boat
	Shape circleFishing = new Ellipse2D.Double(xPosition,yPosition,10,10); // fishing boat
	Shape circleCargo = new Ellipse2D.Double(xPosition,yPosition,10,10); // cargo vessel
	Shape circlePassenger = new Ellipse2D.Double(xPosition,yPosition,10,10); // passenger vessel
	private double finalX = 530;
	private double finalY = 100;
	Line2D line = new Line2D.Double(530, 425, finalX, finalY);
	Line2D line2 = new Line2D.Double(530, 425, finalX, finalY);
	Icon swimmerImage = new ImageIcon("swimmer.jpg");
	Icon speedImage = new ImageIcon("speed.jpg");
	Icon fishingImage = new ImageIcon("fishing.jpg");
	Icon cargoImage = new ImageIcon("cargo.jpg");
	Icon passengerImage = new ImageIcon("passenger.jpg");
	VesselList fList;
	private double range;
	private double angle = 0;
	private double angle2 = 0;
	private double realFinalX = 530;
	private double realFinalY = 100;
	
	public gridUI(initUI initial, tableUI tab, LoadSystem system){
		
		setTitle("2-D Grid"); // sets window title
		setSize(WINDOW_WIDTH, WINDOW_HEIGHT); // sets window size
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // close when red X is clicked
		this.system = system;
		buildButtonPanel();
		buildSliderPanel();
		buildRadarPanel();
		buildCheckBoxPanel();
		add(checkBoxPanel, BorderLayout.WEST);
		add(sliderPanel, BorderLayout.SOUTH);
		add(buttonPanel, BorderLayout.NORTH); // adds button panel to frame
		add(radarPanel, BorderLayout.CENTER);
		init = initial;
		table = tab;
		range = system.getInfo().getRange();
	}
	
	private int convertX(double x){
		
		x = ((x + range) * (660.0/(range * 2)) + 200);
		return (int) x;
	}
	
	private int convertY(double y){
		
		y = -((y - range) * (660.0/(range * 2))) + 100;
		return (int) y;

	}
	
	private void buildButtonPanel(){
		
		startPauseButton = new JButton("Start"); // creates start Button
		startPauseButton.setBackground(Color.GREEN);
		startPauseButton.addActionListener(new ButtonListener());
		gridBackButton = new JButton("Back to Menu"); // creates back to menu button
		gridBackButton.addActionListener(new ButtonListener()); //adds listener to back to menu button
		tableFromGrid = new JButton("Table"); // creates table button
		tableFromGrid.addActionListener(new ButtonListener()); // adds listener to table button
		dualView = new JButton("Dual-View");
		dualView.addActionListener(new ButtonListener());
		buttonPanel = new JPanel(); // creates panel
		buttonPanel.setBackground(Color.BLACK);
		buttonPanel.add(startPauseButton); // adds start/pause button
		buttonPanel.add(gridBackButton); // adds back to menu button
		buttonPanel.add(tableFromGrid); // adds grid button
		buttonPanel.add(dualView); // adds dual view button
	}
	
	private void buildSliderPanel(){ // NOT DONE ACTION LISTENER
			
			timeStep = new JLabel("TIMESTEP (in milliseconds): ");
			timeStep.setForeground(Color.ORANGE);
			slider = new JSlider(JSlider.HORIZONTAL, 500, 5000, (init.system.getInfo().getTimeStep() * 1000));
			slider.setPreferredSize(new Dimension(300,90));
			slider.setMajorTickSpacing(500);
			slider.setMinorTickSpacing(100);
			slider.setPaintTicks(true);
			slider.setPaintLabels(true);
			slider.setBackground(Color.BLACK);
			slider.setForeground(Color.ORANGE);
			sliderPanel = new JPanel();
			sliderPanel.setBackground(Color.BLACK);
			slider.addChangeListener(new SliderListener());
			
			sliderPanel.add(timeStep);
			sliderPanel.add(slider);
	}
	
	private void buildRadarPanel(){
		
		radarPanel = new JPanel();
		radarPanel.setBackground(Color.BLACK);
		addMouseListener(new MyMouseListener());
	}
	
	private void buildCheckBoxPanel(){ // NOT DONE ACTION LISTENERS OR SCROLL BAR
		
		checkBoxPanel = new JPanel();
		checkBoxPanel.setLayout(new GridLayout(initUI.shipTypes.length + 2, 1));
		checkBoxPanel.setBackground(Color.BLACK);
		checkBoxPanel.setBorder(BorderFactory.createLineBorder(Color.ORANGE, 4));
		vessels = new JLabel("Vessel Filtering:");
		vessels.setBackground(Color.BLACK);
		vessels.setForeground(Color.ORANGE);
		timerField = new JTextField(); 
		timerField.setText("Time Elapsed: 0.0s");
		timerField.setEditable(false);
		timerField.setFont(timerField.getFont().deriveFont(Font.BOLD));
		timerField.setForeground(Color.GREEN);
		timerField.setBackground(Color.BLACK);
		timerField.setBorder(BorderFactory.createLineBorder(Color.ORANGE, 1));
		checkBoxPanel.add(timerField);		
		checkBoxPanel.add(vessels);
		swimmer = new JCheckBox(initUI.shipTypes[0], true);
		swimmer.addActionListener(new CheckBoxListener());
		speedBoat = new JCheckBox(initUI.shipTypes[1], true);
		speedBoat.addActionListener(new CheckBoxListener());
		fishingBoat = new JCheckBox(initUI.shipTypes[2], true);
		fishingBoat.addActionListener(new CheckBoxListener());
		cargoVessel = new JCheckBox(initUI.shipTypes[3], true);
		cargoVessel.addActionListener(new CheckBoxListener());
		passengerVessel = new JCheckBox(initUI.shipTypes[4], true);
		passengerVessel.addActionListener(new CheckBoxListener());
		swimmer.setBackground(Color.BLACK);
		swimmer.setForeground(Color.RED);
		speedBoat.setBackground(Color.BLACK);
		speedBoat.setForeground(Color.BLUE);
		fishingBoat.setBackground(Color.BLACK);
		fishingBoat.setForeground(Color.YELLOW);
		cargoVessel.setBackground(Color.BLACK);
		cargoVessel.setForeground(Color.WHITE);
		passengerVessel.setBackground(Color.BLACK);
		passengerVessel.setForeground(Color.GREEN);
		checkBoxPanel.add(swimmer);
		checkBoxPanel.add(speedBoat);
		checkBoxPanel.add(fishingBoat);
		checkBoxPanel.add(cargoVessel);
		checkBoxPanel.add(passengerVessel);
	}
	
	public void paint(Graphics g){ // Overridden paint method		
		super.paint(g);
		g.setColor(Color.BLACK);
		g.drawOval(500, 400, 60, 60);
		g.setColor(Color.ORANGE);
		g.fillOval(520, 423, 20, 20);
		g.setColor(Color.GREEN);
		g.drawOval(450, 350, 160, 160);
		g.drawOval(400, 300, 260, 260);
		g.drawOval(350, 250, 360, 360);
		g.drawOval(300, 200, 460, 460);
		g.drawOval(250, 150, 560, 560);
		g.drawOval(200, 100, 660, 660);
		g.setColor(Color.ORANGE);
		g.drawRect(200, 100, 660, 660);
		g.setColor(Color.GREEN);
		Graphics2D gShapes = (Graphics2D)g;
		

		fList = new VesselList();
		VesselList currentVessels = system.getCurrentVessels();
		for (int i = 0; i < currentVessels.getPointer(); i++) {
			Vessel v = currentVessels.getVesselAtIndex(i);
			if (v != null && checkTypeID(v.getType())) {
				fList.add(v);
			}
		}
		
		//LINE ROTATION
		Graphics2D gLine = (Graphics2D)g;
		finalX = 530 + 325*Math.sin(angle);
		finalY = 425 - 325*Math.cos(angle);
		line = new Line2D.Double(530, 425, finalX, finalY); // 530, 425, 530, 100
		gLine.setPaint(Color.GREEN);
		gLine.draw(line);
		angle += (Math.PI/4);
		
		
		// SHIPS
		for(int i = 0; i < fList.getPointer(); i++){
			
			xPosition = convertX(fList.getVesselAtIndex(i).getXPosition());
			yPosition = convertY(fList.getVesselAtIndex(i).getYPosition());
			index = i;
			
			if(fList.getVesselAtIndex(i).getType() == 1){
				circleHuman = new Ellipse2D.Double(xPosition,yPosition,10,10); // human (swimmer)
				gShapes.setPaint(Color.RED);
				gShapes.draw(circleHuman);
				gShapes.fill(circleHuman);
			}
			else if(fList.getVesselAtIndex(i).getType() == 2){
				circleSpeed = new Ellipse2D.Double(xPosition,yPosition,10,10); // speed boat
				gShapes.setPaint(Color.BLUE);
				gShapes.draw(circleSpeed);
				gShapes.fill(circleSpeed);
			}
			else if(fList.getVesselAtIndex(i).getType() == 3){
				circleFishing = new Ellipse2D.Double(xPosition,yPosition,10,10); // fishing boat
				gShapes.setPaint(Color.YELLOW);
				gShapes.draw(circleFishing);
				gShapes.fill(circleFishing);
			}
			else if(fList.getVesselAtIndex(i).getType() == 4){
				circleCargo = new Ellipse2D.Double(xPosition,yPosition,10,10);
				gShapes.setPaint(Color.WHITE); // cargo vessel
				gShapes.draw(circleCargo);
				gShapes.fill(circleCargo);
			}
			else if(fList.getVesselAtIndex(i).getType() == 5){
				circlePassenger = new Ellipse2D.Double(xPosition,yPosition,10,10); // passenger vehicle
				gShapes.setPaint(Color.GREEN);
				gShapes.draw(circlePassenger);
				gShapes.fill(circlePassenger);
			}
			else{
				System.out.println("Unexpected error");
				System.exit(0);
			}
		}

		for(int i = 0; i < system.getAlarms().getPointer(); i++){
			
			if (checkTypeID(system.getAlarms().getAlarmAtIndex(i).getVesselX().getType()) & checkTypeID(system.getAlarms().getAlarmAtIndex(i).getVesselY().getType())){
				
				if(system.getAlarms().getAlarmAtIndex(i).getAlarmType() == 'h'){
					
					g.setColor(Color.RED);
					g.drawOval(convertX(system.getAlarms().getAlarmAtIndex(i).getVesselX().getXPosition()) - 5, convertY(system.getAlarms().getAlarmAtIndex(i).getVesselX().getYPosition()) - 5, 20, 20);
					g.drawOval(convertX(system.getAlarms().getAlarmAtIndex(i).getVesselY().getXPosition()) - 5, convertY(system.getAlarms().getAlarmAtIndex(i).getVesselY().getYPosition()) - 5, 20, 20);
				}
				if(system.getAlarms().getAlarmAtIndex(i).getAlarmType() == 'l'){
					g.setColor(Color.YELLOW);
					g.drawOval(convertX((int)system.getAlarms().getAlarmAtIndex(i).getVesselX().getXPosition()) - 5, convertY((int)system.getAlarms().getAlarmAtIndex(i).getVesselX().getYPosition()) - 5, 20, 20);
					g.drawOval(convertX((int)system.getAlarms().getAlarmAtIndex(i).getVesselY().getXPosition()) - 5, convertY((int)system.getAlarms().getAlarmAtIndex(i).getVesselY().getYPosition()) - 5, 20, 20);
				}
			}
		}
	}
	
	private boolean checkTypeID(int ID) {
		switch (ID) {
		case 1: return swimmer.isSelected();
		case 2: return speedBoat.isSelected();
		case 3: return fishingBoat.isSelected();
		case 4: return cargoVessel.isSelected();
		case 5: return passengerVessel.isSelected();
		default: return true;
		}
	}
	
	private class ButtonListener implements ActionListener{
		
		public void actionPerformed(ActionEvent e){
			
			if (e.getSource() == startPauseButton){
				if (startPauseButton.getText() == "Start"){
					startPauseButton.setText("Pause");
					startPauseButton.setBackground(Color.RED);
					table.startPauseButton.setText("Pause");
					table.startPauseButton.setBackground(Color.RED);
					init.timer.setInitialDelay(slider.getValue());
					init.timer.start(); // starts data
					init.secondTimer.start();
				}
				else{
					startPauseButton.setText("Start");
					startPauseButton.setBackground(Color.GREEN);
					table.startPauseButton.setText("Start");
					table.startPauseButton.setBackground(Color.GREEN);
					init.timer.stop(); // stops data
					init.secondTimer.stop();
				}
			}
			else if (e.getSource() == gridBackButton){ // if back button was pressed
				setVisible(false); // remove grid visibility
				init.setVisible(true); // make initial UI visible
			}
			else if(e.getSource() == tableFromGrid){ // if table button was pressed
				
				setVisible(false); // remove grid visibility
				table.setVisible(true); // make table visible
			}
			else if(e.getSource() == dualView){
				
				table.setVisible(true);
			}
		}
	}
	
	private class CheckBoxListener implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			
			if (initUI.optionSelected.equals("Administrator")){
				
				if (e.getSource() == swimmer) table.swimmer.setSelected(swimmer.isSelected());
				else if (e.getSource() == speedBoat) table.speedBoat.setSelected(speedBoat.isSelected());
				else if (e.getSource() == fishingBoat) 	table.fishingBoat.setSelected(fishingBoat.isSelected());
				else if (e.getSource() == cargoVessel)  table.cargoVessel.setSelected(cargoVessel.isSelected());
				else if (e.getSource() == passengerVessel) table.passengerVessel.setSelected(passengerVessel.isSelected());
			}
			else{
				if (e.getSource() == swimmer) swimmer.setSelected(true);
				else if (e.getSource() == speedBoat) speedBoat.setSelected(true);
				else if (e.getSource() == fishingBoat) fishingBoat.setSelected(true);
				else if (e.getSource() == cargoVessel) cargoVessel.setSelected(true);
				else if (e.getSource() == passengerVessel) passengerVessel.setSelected(true);
				
				JOptionPane.showMessageDialog(null, "Please sign in as admin to have filtering privileges", "Guest Account", JOptionPane.ERROR_MESSAGE);

			}

		}
	}
	
	private class SliderListener implements ChangeListener{
		
		public void stateChanged(ChangeEvent e){
			initUI.currentSliderValue = slider.getValue();
			tableUI.slider.setValue(slider.getValue());
			init.timer.setDelay(slider.getValue()); // sets timer delay to new slider value
		}
	}
	
	private class MyMouseListener implements MouseListener{
		
		public void mouseClicked(MouseEvent e){
			
			if(circleHuman.contains(e.getX(), e.getY())){
				JOptionPane.showMessageDialog(null, "Human (Swimmer) ", "Additional Information", 1, swimmerImage);
	
			}
			else if (circleSpeed.contains(e.getX(), e.getY())){
				
				JOptionPane.showMessageDialog(null, "Speed Boat\nID: " + system.getCurrentVessels().getVesselAtIndex(index).getID() 
						+ "\nPosition: " + "(" + system.getCurrentVessels().getVesselAtIndex(index).getXPosition() + " , " + 
						system.getCurrentVessels().getVesselAtIndex(index).getYPosition() + ")", "Additional Information", 1, speedImage);
			}
			else if (circleFishing.contains(e.getX(), e.getY())){
				
				JOptionPane.showMessageDialog(null, "Fishing Boat\nID: " + system.getCurrentVessels().getVesselAtIndex(index).getID() 
						+ "\nPosition: " + "(" + system.getCurrentVessels().getVesselAtIndex(index).getXPosition() + " , " + 
						system.getCurrentVessels().getVesselAtIndex(index).getYPosition() + ")", "Additional Information", 1, fishingImage);
			}
			else if (circleCargo.contains(e.getX(), e.getY())){
				
				JOptionPane.showMessageDialog(null, "Cargo Vessel\nID: " + system.getCurrentVessels().getVesselAtIndex(index).getID() 
						+ "\nPosition: " + "(" + system.getCurrentVessels().getVesselAtIndex(index).getXPosition() + " , " + 
						system.getCurrentVessels().getVesselAtIndex(index).getYPosition() + ")", "Additional Information", 1, cargoImage);
			}
			else if (circlePassenger.contains(e.getX(), e.getY())){
				
				JOptionPane.showMessageDialog(null, "Passenger Vessel\nID: " + system.getCurrentVessels().getVesselAtIndex(index).getID() 
						+ "\nPosition: " + "(" + system.getCurrentVessels().getVesselAtIndex(index).getXPosition() + " , " + 
						system.getCurrentVessels().getVesselAtIndex(index).getYPosition() + ")", "Additional Information", 1, passengerImage);
			}
			
		}
		
		// Overridden methods
		public void mousePressed(MouseEvent e){}		
		public void mouseReleased(MouseEvent e){}	
		public void mouseEntered(MouseEvent e){}	
		public void mouseExited(MouseEvent e){}
	}



}
